<template>
  <section id="map" ref="map" class="map-box"></section>
</template>

<script>
  import AMap from 'AMap'
  import AMapUI from 'AMapUI'

  export default {
    name: 'BaseMap',
    data() {
      return {
        map: null,
        markers: [],
        iconMarkers: [],
        lineMarkers: [],
        linePointMarker: [],
        lastMarker: null,
        lastMarkerColor: null,
        zoom: 13,
        pathSimplifierIns: null,
        // dom标记点
        htmlMarkers: {}
      }
    },
    mounted() {
      this.initMap()
    },
    methods: {
      initMap() {
        this.map = new AMap.Map('map', {
          center: [118.268927, 33.968948],
          mapStyle: 'amap://styles/92e46b2be919d4a6b1dc14915ee8b2a0', // 设置地图的显示样式
          resizeEnable: true,
          zoom: this.zoom
        })
      },
      // 添加点
      addCircleMarkers(data, target, option = {
                                      clearFlag: true,
                                      fitViewFlag: true,
                                      clickFlag: true,
                                      radius: 7,
                                      fillColor: 'rgba(0,255,0,1)',
                                      fillOpacity: 1
                                    }, clickColor = 'rgba(235,97,0,1)') {
        if (option.clearFlag) {
          this.clearMarkers()
        }
        data.forEach(item => {
          const center = [Number(item.lng), Number(item.lat)]
          item.markerType = target
          const circleMarker = new AMap.CircleMarker({
            center: center,
            radius: option.radius || 7,
            strokeColor: 'white',
            strokeWeight: 0,
            strokeOpacity: option.strokeOpacity || 0,
            fillColor: option.fillColor || 'rgba(0,255,0,1)',
            fillOpacity: option.fillOpacity || 1,
            zIndex: 10,
            bubble: true,
            cursor: 'pointer',
            clickable: true,
            extData: item
          })
          // 点击事件
          if (option.clickFlag) {
            circleMarker.on('click', e => {
              this.circleMarkerClick(e, clickColor)
            })
          }

          this.markers.push(circleMarker)
        })

        this.map.add(this.markers)
        // 自动调整层级
        if (option.fitViewFlag) {
          this.map.setFitView()
        }
      },
      // 圆形点点击事件
      circleMarkerClick(e, clickColor) {
        // 上一个点击点变色回来
        if (this.lastMarker !== null) {
          this.lastMarker.target.setOptions({map: this.map, fillColor: this.lastMarkerColor || 'rgba(0,255,0,1)'})
        }
        // 当前点变色
        this.lastMarkerColor = e.target.getOptions().fillColor
        e.target.setOptions({map: this.map, fillColor: clickColor})
        this.lastMarker = e

        // 其他操作
        this.$emit('circleMarkerClick', e.target.getExtData())
      },
      // 清除点
      clearMarkers() {
        if (this.markers.length > 0) {
          this.map.remove(this.markers)
          this.markers = []
        }
        if (this.lastMarker !== null) {
          this.map.remove(this.lastMarker)
          this.lastMarker = null
        }
        if (this.iconMarkers.length > 0) {
          this.map.remove(this.iconMarkers)
          this.iconMarkers = []
        }
        if (this.lineMarkers.length > 0) {
          this.map.remove(this.lineMarkers)
          this.lineMarkers = []
        }
        if (this.map !== null) {
          this.map.clearMap()
        }
      },
      // 添加icon点
      addIconMarkers(data, img, type = 'default', option = {size: [61, 103], offset: [-30, -87]}, clickFlag = true, fitViewFlag = true, clearFlag = true, showFlag = true) {
        if (clearFlag) {
          this.clearMarkers()
        }
        data.forEach(item => {
          item.markerType = type || 'default'
          const icon = new AMap.Icon({
            size: new AMap.Size(option.size[0] || 61, option.size[1] || 103), // 图标尺寸
            image: img, // Icon的图像
            imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
            imageSize: new AMap.Size(option.size[0] || 61, option.size[1] || 103) // 根据所设置的大小拉伸或压缩图片
          })
          const marker = new AMap.Marker({
            position: new AMap.LngLat(Number(item.lng), Number(item.lat)),
            offset: new AMap.Pixel(option.offset[0] || -30, option.offset[1] || -87),
            icon: icon, // 添加 Icon 实例
            title: item.name || '',
            zoom: this.zoom,
            extData: item
          })
          if (clickFlag) {
            marker.on('click', e => {
              this.iconMarkerClick(e)
            })
          }
          if (showFlag) {
            marker.setLabel({
              offset: new AMap.Pixel(0, 0),
              content: item.name,
              direction: 'bottom'
            })
          }
          this.iconMarkers.push(marker)
        })
        this.map.add(this.iconMarkers)
        // 自动调整层级
        if (fitViewFlag) {
          this.map.setFitView()
        }
      },
      iconMarkerClick(e) {
        this.$emit('iconMarkerClick', e.target.getExtData())
      },
      // 添加icon点，可以指定选中的图标
      addIconMarkers2(data, img, selectedImg, type = 'default', option = {size: [61, 103], offset: [-30, -87]}, clickFlag = true, fitViewFlag = true, clearFlag = true, showFlag = true) {
        const selectedIcon = new AMap.Icon({
            size: new AMap.Size(option.size[0] || 61, option.size[1] || 103), // 图标尺寸
            image: selectedImg, // Icon的图像
            imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
            imageSize: new AMap.Size(option.size[0] || 61, option.size[1] || 103) // 根据所设置的大小拉伸或压缩图片
        })
        if (clearFlag) {
          this.clearMarkers()
        }
        data.forEach(item => {
          item.markerType = type || 'default'
          const icon = new AMap.Icon({
            size: new AMap.Size(option.size[0] || 61, option.size[1] || 103), // 图标尺寸
            image: img, // Icon的图像
            imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
            imageSize: new AMap.Size(option.size[0] || 61, option.size[1] || 103) // 根据所设置的大小拉伸或压缩图片
          })
          const marker = new AMap.Marker({
            position: new AMap.LngLat(Number(item.lng), Number(item.lat)),
            offset: new AMap.Pixel(option.offset[0] || -30, option.offset[1] || -87),
            icon: icon, // 添加 Icon 实例
            title: item.name || '',
            zoom: this.zoom,
            extData: item
          })
          if (clickFlag) {
            marker.on('click', e => {
              this.iconMarkerClick2(e, icon, selectedIcon)
            })
          }
          if (showFlag) {
            marker.setLabel({
              offset: new AMap.Pixel(0, 0),
              content: item.name,
              direction: 'bottom'
            })
          }
          this.iconMarkers.push(marker)
        })
        this.map.add(this.iconMarkers)
        // 自动调整层级
        if (fitViewFlag) {
          this.map.setFitView()
        }
      },
      iconMarkerClick2(e, icon, selectedIcon) {
        this.map.setZoomAndCenter(this.map.getZoom(), e.target.getPosition())
        for (var i = 0; i < this.iconMarkers.length; i++) {
            this.iconMarkers[i].setIcon(icon)
        }
        e.target.setIcon(selectedIcon)
        this.$emit('iconMarkerClick', e.target.getExtData())
      },
      addLineMarker(data) {
        // 添加线
        this.clearMarkers()
        data.forEach(item => {
          const pathArr = item.path
          const stops = item.via_stops
          const startStop = item.name + '-' + item.start_stop
          const endStop = item.name + '-' + item.end_stop
          const startPot = stops[0].location
          const endPot = stops[stops.length - 1].location
          this.drawbusLine(startPot, endPot, pathArr, startStop, endStop)
        })
      },
      drawbusLine(startPot, endPot, BusArr, startStop, endStop) {
        // 绘制起点，终点
        const marker = new AMap.Marker({
          map: this.map,
          position: startPot, // 基点位置
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
          zIndex: 10
        })
        marker.setLabel({
          offset: new AMap.Pixel(0, 0),
          content: startStop,
          direction: 'bottom'
        })
        const marker1 = new AMap.Marker({
          map: this.map,
          position: endPot, // 基点位置
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
          label: 1111,
          zIndex: 10
        })
        marker1.setLabel({
          offset: new AMap.Pixel(0, 0),
          content: endStop,
          direction: 'bottom'
        })
        this.linePointMarker.push(marker)
        this.linePointMarker.push(marker1)
        this.map.add(this.linePointMarker)
        // 绘制乘车的路线
        const busPolyline = new AMap.Polyline({
          path: BusArr,
          strokeColor: '#09f', // 线颜色
          strokeOpacity: 0.8, // 线透明度
          isOutline: true,
          outlineColor: 'white',
          strokeWeight: 6// 线宽
        })
        this.lineMarkers.push(busPolyline)
        this.map.add(this.lineMarkers)
      },
      setZoom(level) {
        this.map.setZoom(level)
      },
      setCenter(lng, lat) {
        const postion = [lng, lat]
        this.map.setCenter(postion)
      },
      drawPathAndMove(data, speed = 100, loop = false) {
        // const img = require("../../../assets/image/yxqk/move_person1.gif");
        const img = require('../../../assets/image/base/car_normal.png')
        AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], (PathSimplifier, $) => {
          if (!PathSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas！')
            return
          }
          this.clearPathAndMove()
          if (!this.pathSimplifierIns) {
            this.pathSimplifierIns = new PathSimplifier({
              zIndex: 115,
              // autoSetFitView:false,
              map: this.map, // 所属的地图实例

              getPath: function(pathData, pathIndex) {
                return pathData.path
              },
              getHoverTitle: function(pathData, pathIndex, pointIndex) {
                // if (pointIndex >= 0) {
                //   // point
                //   return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length
                // }
                //
                // return pathData.name + '，点数量' + pathData.path.length
              },
              renderOptions: {
                pathLineStyle: {
                  lineWidth: 3,
                  strokeStyle: '#4293F4',
                  borderWidth: 1,
                  borderStyle: '#eeeeee99',
                  dirArrowStyle: false
                },
                pathNavigatorStyle: {
                  initRotateDegree: 270,
                  width: 41,
                  height: 25,
                  content: PathSimplifier.Render.Canvas.getImageContent(
                    img,
                    onload,
                    onerror
                  ),
                  // autoRotate: false,
                  autoRotate: true,
                  lineJoin: 'round',
                  // content: "defaultPathNavigator",
                  fillStyle: '#087EC4',
                  strokeStyle: '#116394',
                  lineWidth: 1,
                  pathLinePassedStyle: {
                    lineWidth: 2,
                    strokeStyle: '#30DFBA',
                    borderWidth: 1,
                    borderStyle: '#eeeeee',
                    dirArrowStyle: false
                  }
                },
                renderAllPointsIfNumberBelow: 100 // 绘制路线节点，如不需要可设置为-1
              }
            })
          }

          // 设置数据
          this.pathSimplifierIns.setData(data)
          // 对第一条线路（即索引 0）创建一个巡航器
          var navg1 = this.pathSimplifierIns.createPathNavigator(0, {
            loop: loop, // 循环播放
            speed: speed // 巡航速度，单位千米/小时,
          })
          navg1.start()
        })
      },
      clearPathAndMove() {
        if (this.pathSimplifierIns) {
          this.pathSimplifierIns.setData([])
        }
      },
      addHtmlMarkers(data, options) {
        const optionDefault = {
          pixel: [6, 6],
          type: 'default',
          clickFlag: true,
          clearFlag: true
        }
        const option = Object.assign({ ...optionDefault }, options)

        if (this.htmlMarkers[option.type] === undefined) {
          this.htmlMarkers[option.type] = []
        }

        if (option.clearFlag) {
          this.clearHtmlMarkers(option.type)
        }

        data.forEach(item => {
          const marker = new AMap.Marker({
            content: item.content || ' ', // 自定义点标记覆盖物内容
            position: item.position || [0, 0], // 基点位置
            offset: new AMap.Pixel(option.pixel[0], option.pixel[1]), // 相对于基点的偏移位置
            extData: item
          })

          if (option.clickFlag) {
            marker.on('click', e => {
              this.$emit(option.type + 'HtmlMarkerClick', e.target.getExtData())
            })
          }

          this.htmlMarkers[option.type].push(marker)
        })
        //
        this.map.add(this.htmlMarkers[option.type])
      },
      clearHtmlMarkers(type = 'default') {
        if (this.htmlMarkers[type] && this.htmlMarkers[type].length > 0) {
          this.map.remove(this.htmlMarkers[type])
          this.htmlMarkers[type] = []
        }
      }
    }
  }
</script>

<style scoped>
  .map-box {
    width: 100%;
    height: 100%;
  }

  /deep/ .amap-logo {
    display: none !important;
  }
  /deep/ .amap-marker-label {
    background-color: transparent !important;
    border: none !important;
  }
</style>
